package com.wikilife;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.oklib.base.CoreBaseFragment;
import com.oklib.utils.logger.Logger;
import com.wikilife.index.NetworkImageHolderView;
import com.wikilife.index.contract.IndexContract;
import com.wikilife.index.model.IndexBanner;
import com.wikilife.index.model.IndexEntrance;
import com.wikilife.index.model.IndexModel;
import com.wikilife.index.model.IndexRecommend;
import com.wikilife.index.presenter.IndexPresenter;
import com.wikilife.widget.BannerHolderView;
import com.wikilife.widget.HackConvenientBanner;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Damon.Han on 2017/2/17 0017.
 *
 * @author Damon
 */

public class FragmentIndex extends CoreBaseFragment<IndexPresenter, IndexModel> implements IndexContract.View {
    List<Fragment> fragments = new ArrayList<>();
    //    @BindView(R.id.recycler_recommends)
//    CoreRecyclerView recyclerViewRecommends;
    @BindView(R.id.banner)
    HackConvenientBanner hackConvenientBanner;
    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.frg_index_marqee_left)
    TextView frgIndexMarqeeLeft;
    @BindView(R.id.frg_index_marqee_content)
    TextView frgIndexMarqeeContent;
    @BindView(R.id.topPanel)
    FrameLayout topPanel;
    @BindView(R.id.spinner_txt)
    TextView spinnerTxt;
    private ConvenientBanner convenientBanner;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_index;
    }

    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {


//        recyclerViewRecommends.init(new GridLayoutManager(getContext(), 3), new BaseQuickAdapter<IndexRecommend, BaseViewHolder>(R.layout.layout_index_item_recommend) {
//            @Override
//            protected void convert(BaseViewHolder helper, IndexRecommend item) {
//                helper.setText(R.id.txt_title, item.title);
//                helper.setText(R.id.txt_sub_title, item.subTitle);
//
//                ImageLoaderUtil.getInstance().loadImage(getContext(),
//                        new ImageLoader.Builder().imgView((ImageView) helper.getView(R.id.img)).url(item.url).build());
//
//            }
//        });
    }

    @Override
    public void initData() {
//        mPresenter.getBannerData();
        convenientBanner = (ConvenientBanner) LayoutInflater.from(getContext()).inflate(R.layout.adapter_header_cb, null);
        List<List<IndexEntrance>> data = new ArrayList<>();
        initEntranceData(data, 0, 9);
        initEntranceData(data, 10, 19);

        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, data).setPageIndicator(new int[]{R.drawable.page_indicator_color_gray, R.drawable.page_indicator_color_primary});

//        convenientBanner.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,600));
        //推荐数据
//        mPresenter.getRecommendsData();
        topPanel.addView(convenientBanner);
        frgIndexMarqeeLeft.setText(Html.fromHtml("百科<font color='red'>头条</font>"));
        setTextMarquee(frgIndexMarqeeContent);
    }

    private List<List<IndexEntrance>> initEntranceData(List<List<IndexEntrance>> data, int start, int end) {
        String[] txts = getResources().getStringArray(R.array.index_top_items);
        IndexEntrance indexTopItem = null;
        List<IndexEntrance> indexTopItems = new ArrayList<>();
        for (int i = start; i <= end; i++) {
            indexTopItem = new IndexEntrance();
            indexTopItem.text = txts[i];
            int drawableId = getResources().getIdentifier("ic_category_" + i, "mipmap", getContext().getPackageName());
            indexTopItem.drawId = drawableId;
            indexTopItems.add(indexTopItem);
        }
        data.add(indexTopItems);
        return data;
    }

    public static void setTextMarquee(TextView textView) {
        if (textView != null) {
            textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
            textView.setSingleLine(true);
            textView.setSelected(true);
            textView.setFocusable(true);
            textView.setFocusableInTouchMode(true);
        }
    }

    /**
     * 初始顶部banner
     *
     * @param indexBanners
     */
    private void initBanners(List<IndexBanner> indexBanners) {
        hackConvenientBanner.setPages(new CBViewHolderCreator<BannerHolderView>() {
            @Override
            public BannerHolderView createHolder() {
                return new BannerHolderView();
            }
        }, indexBanners)
                // 设置两个点图片作为翻页指示器，不设置则没有指示器
                .setPageIndicator(new int[]{R.mipmap.ic_page_indicator_gray, R.mipmap.ic_page_indicator_focused_blue})
                // 设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        showToast(indexBanners.get(position).title);
                    }
                });
        // .setManualPageable(false); // 设置不能手动影响(手指不能滑动);
        // 控制是否循环
        if (indexBanners.size() == 1) {
            hackConvenientBanner.setCanLoop(false);
        } else {
            hackConvenientBanner.setCanLoop(true);
        }
    }

    @Override
    public void showIndexBanner(List<IndexBanner> indexBanners) {
        initBanners(indexBanners);
    }

    @Override
    public void showIndexEntrance(List<IndexEntrance> indexEntrances) {

    }

    @Override
    public void showRecommends(List<IndexRecommend> indexRecommends) {
//        recyclerViewRecommends.getAdapter().addData(indexRecommends);
//        recyclerViewRecommends.addOnItemClickListener(new com.oklib.widget.recyclerview.listener.OnItemClickListener() {
//            @Override
//            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
//                showToast(indexRecommends.get(position).title);
//            }
//        });
    }

    @Override
    public void showMsg(String msg) {

    }


    @OnClick(R.id.spinner_txt)
    public void onClick() {
        startActivity(new Intent(mContext, PoiAroundSearchActivity.class));
        Logger.e(Test.sHA1(mContext));
    }

    private class DividerGridItemDecoration extends RecyclerView.ItemDecoration {

        public DividerGridItemDecoration(Context context) {
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            int pos = parent.getChildAdapterPosition(view);
            outRect.top = 20;
            if (pos != 0) {
                if ((pos + 1) % 3 != 0) {
                    outRect.right = 20;
                }
            } else {
                outRect.right = 20;
            }
        }
    }
}
